package learning.algorithm.list.linkedlist;

import learning.algorithm.list.AbstractList;
import learning.algorithm.list.List;

public class LinkedList1<E> extends AbstractList<E> {
    Node<E> first;

    public LinkedList1() {
        first = new Node<>(null, null);
    }

    @Override
    public void clear() {
        first = null;
        size = 0;
    }

    @Override
    public E get(int index) {
        rangeCheck(index);
        return node(index).element;
    }

    @Override
    public E set(int index, E element) {
        rangeCheck(index);
        Node<E> node = node(index);
        E oldElement = node.element;
        node.element = element;
        return oldElement;
    }

    @Override
    public void add(int index, E element) {
        rangeCheckForAdd(index);
        Node<E> prev = index == 0 ? first : node(index - 1);
        prev.next = new Node<>(element, prev.next);
        size++;
    }

    @Override
    public E remove(int index) {
        rangeCheck(index);
        Node<E> prev = index == 0 ? first : node(index - 1);
        Node<E> node = prev.next;
        E oldElement = node.element;
        prev.next = node.next;
        size--;
        return oldElement;
    }

    @Override
    public int indexOf(E element) {
        Node<E> tmp = first.next;
        if (element == null) {
            for (int i = 0; i < size; i++) {
                if (tmp.element == null) {
                    return i;
                }
                tmp = tmp.next;
            }
        } else {
            for (int i = 0; i < size; i++) {
                if (tmp.element.equals(element)) {
                    return i;
                }
                tmp = tmp.next;
            }
        }
        return List.ELEMENT_NOT_FOUND;
    }

    private Node<E> node(int index) {
        rangeCheck(index);
        Node<E> node = first.next;
        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node;
    }

    private static class Node<E> {
        E element;
        Node<E> next;

        public Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }
    }
}
